<!--
*@Author: QWP
*@Description: 树形下拉选择器
*@Date: 2024-10-22 14:57:08
-->
<template>
  <a-tree-select
    v-bind="$attrs"
    v-model:value="value"
    :treeData="treeData1"
    :show-search="$attrs['showSearch'] || true"
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :allow-clear="$attrs['allow-clear'] || true"
    :tree-default-expand-all="$attrs['tree-default-expand-all'] || true"
    tree-node-filter-prop="label"
    @change="change"
  >
  </a-tree-select>
</template>

<script lang='ts' setup>
defineOptions({ name: 'u-tree-select' })
import { ref, reactive, computed, onMounted, watch, useAttrs, isRef } from 'vue' 
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { isRefC } from '@/util/common'

const attrs = useAttrs()
const props = withDefaults(
  defineProps<{
    treeData: any,
    expandedKeys?: any[] | any,
    checkedKeys?: any[] | any,
    value: string | string[] | any,
    resultType?: 'string' | 'Array',
    operator?: string
  }>(),
  {
    resultType: 'string',
    operator: ','
  }
)

const emits = defineEmits(['update:value', 'change'])

const value = ref<string | string[] | any>()

const treeData1 = ref<any[]>([])

const change = (value, label, extra) => {
  if(attrs['multiple'] == true) {
    let tValue = value || []
    let result = props.resultType == 'string' ? tValue.join(props.operator) : tValue
    emits('update:value', result)
  }
  else {
    if(props.resultType == 'string') {
      let tValue = value || ''
      let result = tValue instanceof Array ? (tValue || []).join(props.operator) : tValue
      emits('update:value', result)
    }
    else if(props.resultType == 'Array') {
      let tValue = value || []
      let result = tValue instanceof Array ? tValue : [ tValue ] 
      emits('update:value', result)
    }
  }
  emits('change', value, label, extra)
}

const echoInfo = (nval) => {
  if(attrs['multiple'] == true) {
    if(props.resultType == 'string') {
      let tNval = nval || ''
      value.value = tNval instanceof Array ? tNval : tNval.split(props.operator)
    }
    else if(props.resultType == 'Array') {
      value.value = nval || []
    }
  }
  else {
    value.value = props.resultType == 'string' ? (nval || '') : (nval || [])
  }
}

watch(() => props.value, (nval, oval) => {
  echoInfo(nval)
}, { immediate: true, deep: true })

watch(() => props.treeData, (nval, oval) => {
  treeData1.value = isRefC(nval) ?? [];
  if(props.value) {
    echoInfo(props.value)
  }
}, { deep: true })

</script>

<style lang='scss' scoped>
</style>